var order = {
	payment:"2",				//2微信 1现金
	userId:"",				//用户id
	orderAmount:0,			//订单总额
	couponCardNumber:"",	//优惠券卡号
	discountAmount:0,		//优惠券金额
	actualOrderAmount:0,	//订单实际总额
	courseIds:"",			//课程id
	carData:"",
	purchaseTimesS:"" //课次
	
};

//提交订单
order.submit = function(){
	openLoad();
	var options = {
		payment:order.payment,
		userId:Feng.userId,
		orderState:1,
		orderAmount:order.orderAmount,
		couponCardNumber:order.couponCardNumber,
		discountAmount:order.discountAmount,
		actualOrderAmount:order.actualOrderAmount,
		courseIds:order.courseIds,
		purchaseTimesS:order.purchaseTimesS
	};
	var ajax = new $ax(Feng.ctxPath+"/order/save", function(data){        
		
        if (data.success){
        	Feng.log("订单提交成功");
        	console.log("支付前："+Feng.userId);
        	if(order.payment==="2"){
        		//调用微信支付
        		        
        		if(window.location.hostname!=="wisdom-site.com"){
        			Feng.error("非线上环境无法调用微信支付接口");
        		}
        		else{
        			order.wecatPay(data.obj.id);
        		}
        	}
        	else{
        		layer.confirm('您的订单已提交，请在三天内，到指定线下网点支付即可', {
					btn: ['确定'], //按钮
                    cancel: function(index, layero){
                        window.location.href="my-order.html";
                    }
                },function(){
					window.location.href="my-order.html";
				});
        	}
        	//删除购物车中已被提交订单的货物
        	if(order.carData!=null && order.carData.length>0){
        		var courseIdArry = order.courseIds.split(',');
	        	courseIdArry.forEach(function(order_item){        		
	        		var arryIndex = order.carData.findIndex(function (car_item) {
					    return car_item.id == order_item;
					});	
					
					if(arryIndex>-1){
						order.carData.splice(arryIndex,1);
					}
	        	})
	        	localStorage.setItem("carData",JSON.stringify(order.carData));  
        	}
      	
	
        }
        else if(data.code === 2){
        	Feng.error(data.msg);
        }else if(data.code === 3){
			Feng.error("请在'个人信息'界面绑定手机");
			var a= setTimeout("window.location.href='my-info.html'",2000);
		}
        else{
        	Feng.error("订单提交失败");
        }
        closeLoad();
    },function(data){
    	closeLoad();
        Feng.error("订单提交失败");
    });
    ajax.set(options);
    ajax.start();
};

//初始微信支付信息
order.initPay = function(){
	var url=window.location.href;	
	console.log("回传地址："+url);
	var ajax = new $ax(Feng.ctxPath+"/jsConfig", function(data){
        console.log("初始化微信支付完成");
        console.log(data);
               wx.config({
		            debug: false,
		            appId: data.appId, // 必填，公众号的唯一标识
		            timestamp: data.timestamp, // 必填，生成签名的时间戳
		            nonceStr: data.nonceStr, // 必填，生成签名的随机串
		            signature: data.signature,// 必填，签名，见附录1
		            jsApiList: [
		                'checkJsApi',
		                'onMenuShareTimeline',
		                'onMenuShareAppMessage',
		                'onMenuShareQQ',
		                'onMenuShareWeibo',
		                'onMenuShareQZone',
		                'hideMenuItems',
		                'showMenuItems',
		                'hideAllNonBaseMenuItem',
		                'showAllNonBaseMenuItem',
		                'translateVoice',
		                'startRecord',
		                'stopRecord',
		                'onVoiceRecordEnd',
		                'playVoice',
		                'onVoicePlayEnd',
		                'pauseVoice',
		                'stopVoice',
		                'uploadVoice',
		                'downloadVoice',
		                'chooseImage',
		                'previewImage',
		                'uploadImage',
		                'downloadImage',
		                'getNetworkType',
		                'openLocation',
		                'getLocation',
		                'hideOptionMenu',
		                'showOptionMenu',
		                'closeWindow',
		                'scanQRCode',
		                'chooseWXPay',
		                'openProductSpecificView',
		                'addCard',
		                'chooseCard',
		                'openCard',
		                'getBrandWCPayRequest'
		            ]
		        });
		    
    },function(data){
    	console.log("初始化微信支付失败");
    	console.log(data);        
    });
    ajax.type = "get";
    ajax.set({url:url});
    ajax.start();
}

//微信支付 发送订单ID给微信支付
order.wecatPay = function(orderId){
	console.log("支付前："+Feng.userId);
	if(orderId){	    
	    var ajax = new $ax(Feng.ctxPath+"/pay/"+orderId, function(data){
	    	console.log("微信支付成功");
	        console.log(data);
	         WeixinJSBridge.invoke('getBrandWCPayRequest', {
                "appId": data.obj.appId,                  //公众号名称，由商户传入
                "timeStamp": data.obj.timeStamp,          //时间戳，自 1970 年以来的秒数
                "nonceStr": data.obj.nonceStr,         //随机串
                "package": data.obj.packageStr,      //商品包信息</span>
                "signType": data.obj.signType,        //微信签名方式
                "paySign": data.obj.paySign           //微信签名
            }, function (res) {
                if (res.err_msg == "get_brand_wcpay_request:ok") {// 支付成功
                    Feng.success("您已报名");
                    setTimeout(function(){
                        window.location.href="product_detil_succ.html?orderId="+orderId;
                    },1000);
                } else if (res.err_msg == "get_brand_wcpay_request:cancel") {//支付取消
                } else if (res.err_msg == "get_brand_wcpay_request:fail") {// 支付失败                    
                    Feng.success("支付错误，报名失败");
                }
            });
	    },function(data){
	    	console.log("微信支付失败");
	    	console.log(data);        	        
	        setTimeout(function(){
	        	window.location.href="my-order.html";
	        },1000);
	    });
	    ajax.type = "get";
	    ajax.start();
	}
};




   		
//获取订单信息
order.info =function(){
	openLoad();
	var data = localStorage.getItem("courseData");
	if(data!="") data = JSON.parse(data);
    //价格过滤器
    template.helper('coursePriceFormat', function (inp) {
        if(inp!==""){
            return numeral(inp).format('0,0.00');
        }
    });
    
    //图片过滤器
    template.helper('pictureFormat', function (inp) {
       if(inp){
           return Feng.ctxPath+"/file/getImage/"+inp;
       }
       else{
        	return "themes/img/pd/course_defult.jpg";
       }
    });
    
    //保存订单信息
    var courseIds =[],purchaseTimesArry =[];
    data.forEach(function(item){
    	order.orderAmount += parseFloat(item.actualPrice);    
    	courseIds.push(item.id);
    	purchaseTimesArry.push(item.purchaseTimesS);
    })        
    order.discountAmount = 0;
    order.actualOrderAmount =order.orderAmount;
    order.purchaseTimesS = purchaseTimesArry.toString();
    
    //课程数
    order.courseIds = courseIds.toString();
    
    order.carData = JSON.parse(localStorage.getItem("carData")); 
    
    var outHtml = template("dataTmpl",data);
    $(".aui-address-well").before(outHtml);      
    
    $("#price").html(numeral(order.orderAmount).format('0,0.00'));  
    $("#total-price").html(numeral(order.actualOrderAmount).format('0,0.00'));
    
    closeLoad();
};

//初始化优惠券
order.coupon = function(){
	var options = {
		userId:Feng.userId
	}
	$(".mod_empty_page").show();	
	var ajax = new $ax(Feng.ctxPath+"/couponCardItems/selectParam", function(data){        
        if (data.success && data.obj.length>0){
        	template.helper('dateFormat', function (inp) {
		        if(inp!=="" && inp!==null){
		            return inp.split(' ')[0];
		        }
		        else{
		        	return "永不"
		        }
		    });  
        	
        	var outHtml = template("couponTempl",data.obj);
    		$("#coupon-list").html(outHtml);
    		$("#coupon-list").show();    	
    		$(".mod_empty_page").hide();
    		$("#iscoupon").html("未使用");
        }
        else if(data.code === 2){
        	Feng.open(data.msg);
        }
        else{
        	Feng.log("未查询到优惠券");
        }        
   },function(data){    	
        Feng.log("优惠券查询失败");
    });
    ajax.set(options);
    ajax.start();
}

//确定使用优惠券
$("#btn-confirm-coupon").on("click",function(){		
	$("#cancel-coupon").click();
	if($("[name='coupon']:checked").length>0){
		var coupon =  $("[name='coupon']:checked").attr("data-amount");
		order.couponCardNumber = $("[name='coupon']:checked").val();	
		order.discountAmount = coupon;
		$("#iscoupon").html("-￥"+coupon);
		$("#minus-price").html(coupon);
		order.actualOrderAmount = order.orderAmount-coupon;
		if (order.actualOrderAmount < 0){
            order.actualOrderAmount = 0;
		}
		$("#total-price").html(numeral(order.actualOrderAmount).format('0,0.00'));
	}

});

//选择支付方式
order.pay = function(){
    var $myAs = $('#J_ActionSheet');

    $('#J_ShowActionSheet').on('click', function () {
        $myAs.actionSheet('open');
    });

    $('#J_Cancel').on('click', function () {
        $myAs.actionSheet('close');
    });
}

$("[name='pay']").on("click",function(){
	var pay = $(this).val();
	order.payment = pay;
	
	if(order.payment==="2"){
		$("#pay-method").text("微信支付");
	}
	else if(order.payment==="1"){
		$("#pay-method").text("现金支付");
	}
	else{
		$("#pay-method").text("公司转账");
	}
	$("#cancel").click();
});




$(function(){
	order.info();
	order.pay();		
	order.coupon();	
	order.initPay();
});
